<template>
  <div class="app-container">
    <!-- 对话框(添加 / 修改) -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="800px" v-dialogDrag append-to-body>
      <el-form ref="formRef" :model="formData" :rules="formRules" v-loading="formLoading" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="产品名称" prop="productName">
              <el-input v-model="formData.productName" placeholder="请输入产品名称"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="产品编码" prop="productCode">
              <el-input v-model="formData.productCode" placeholder="请输入产品编码"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="成品物料" prop="materialId">
              <el-select v-model="formData.materialId" filterable remote :remote-method="remoteMethod"
                         :loading="materialLoading" placeholder="请选择物料" style="width: 100%">
                <el-option v-for="item in materialList" :key="item.id" :label="item.materialName" :value="item.id"/>
              </el-select>
            </el-form-item>
          </el-col>
          <!-- <el-col :span="12">
            <el-form-item label="物料编码" prop="materialNo">
              <el-input v-model="formData.materialNo" placeholder="请输入物料编码"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="物料名称" prop="materialName">
              <el-input v-model="formData.materialName" placeholder="请输入物料名称"/>
            </el-form-item>
          </el-col> -->
          <el-col :span="12">
            <el-form-item label="产品类别" prop="category">
              <el-select v-model="formData.category" placeholder="请选择产品类别" clearable filterable size="small"
                         style="width: 100%">
                <el-option v-for="dict in this.getDictDatas(DICT_TYPE.PRODUCT_CATEGORY)" :key="dict.value"
                           :label="dict.label"
                           :value="dict.value"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-radio-group v-model="formData.status">
                <el-radio v-for="dict in this.getDictDatas(DICT_TYPE.COMMON_STATUS)" :key="parseInt(dict.value)"
                          :label="parseInt(dict.value)"
                >
                  {{ dict.label }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm" :disabled="formLoading">确 定</el-button>
        <el-button @click="dialogVisible = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import * as ProductApi from '@/api/basic/product';
import * as MaterialApi from '@/api/basic/material/index.js';
import {getDictDatas, DICT_TYPE} from '@/utils/dict';

export default {
  name: "ProductForm",
  components: {},
  data() {
    return {
      // 弹出层标题
      dialogTitle: "",
      // 是否显示弹出层
      dialogVisible: false,
      // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
      formLoading: false,
      // 表单参数
      formData: {
        id: undefined,
        productName: undefined,
        productCode: undefined,
        materialId: undefined,
        materialNo: undefined,
        materialName: undefined,
        category: undefined,
        status: 1, // 状态默认开启
      },
      // 表单校验
      formRules: {
        status: [{required: true, message: '状态', trigger: 'blur'}],
      },
      // 物料列表相关
      materialList: [],
      materialLoading: false
    };
  },
  // 添加watch监听器，监听materialId的变化
  watch: {
    'formData.materialId': function(newValue) {
      if (newValue && this.materialList.length > 0) {
        // 从物料列表中找到对应的物料
        const selectedMaterial = this.materialList.find(item => item.id === newValue);
        if (selectedMaterial) {
          // 更新物料编码和名称
          this.formData.materialNo = selectedMaterial.materialNo;
          this.formData.materialName = selectedMaterial.materialName;
        }
      } else {
        // 清除已选物料信息
        this.formData.materialNo = undefined;
        this.formData.materialName = undefined;
      }
    }
  },
  methods: {
    /** 打开弹窗 */
    async open(id) {
      this.dialogVisible = true;
      this.reset();
      // 修改时，设置数据
      if (id) {
        this.formLoading = true;
        try {
          const res = await ProductApi.getProduct(id);
          this.formData = res.data;
          this.dialogTitle = "修改产品";
        } finally {
          this.formLoading = false;
        }
      } else {
        this.dialogTitle = "新增产品";
        // 弹出对话框前默认搜索前20条物料
        this.remoteMethod('');
      }
    },
    /** 提交按钮 */
    async submitForm() {
      // 校验主表
      await this.$refs["formRef"].validate();
      this.formLoading = true;
      try {
        const data = this.formData;
        // 修改的提交
        if (data.id) {
          await ProductApi.updateProduct(data);
          this.$modal.msgSuccess("修改成功");
          this.dialogVisible = false;
          this.$emit('success');
          return;
        }
        // 添加的提交
        await ProductApi.createProduct(data);
        this.$modal.msgSuccess("新增成功");
        this.dialogVisible = false;
        this.$emit('success');
      } finally {
        this.formLoading = false;
      }
    },
    /** 表单重置 */
    reset() {
      this.formData = {
        id: undefined,
        productName: undefined,
        productCode: undefined,
        materialId: undefined,
        materialNo: undefined,
        materialName: undefined,
        category: undefined,
        status: 1, // 状态默认开启
      };
      this.resetForm("formRef");
    },

    /** 物料远程搜索方法 */
    async remoteMethod(query) {
      this.materialLoading = true;
      try {
        const params = {
          pageNo: 1,
          pageSize: 20,
          materialName: query
        };
        const res = await MaterialApi.getMaterialPage(params);
        this.materialList = res.data.list;
      } catch (error) {
        console.error('获取物料列表失败:', error);
        this.materialList = [];
      } finally {
        this.materialLoading = false;
      }
    }
  }
};
</script>
